// pages/mine/mineindex.js
const GetPeriod = require("../../utils/getperiod.js");
var util = require("../../utils/util.js");
const MONTHS = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May.', 'June.', 'July.', 'Aug.', 'Sept.', 'Oct.', 'Nov.', 'Dec.'];
const qiniuUploader = require("../../utils/qiniuUploader");
var utils = require('../../utils/util.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showDialog: false,
    name: null,
    photo: null,
    id: null,
    mobile: null,
    photoList: [],
    qiniuToken: "",
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var mobile = wx.getStorageSync('mobile'); //存储用户名
    this.setData({
      mobile: mobile,
      name: app.globalData.name,
      photo: app.globalData.photo,
    })
    console.log(app.globalData.name)
    console.log(app.globalData.photo)
    this.getQiniuToken()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  btnmakephoneclick: function (e) {

    var phone = "400-6610-277";
    wx.showModal({
      title: '拨打电话',
      content: phone,
      success: function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用删除方法了
          wx.makePhoneCall({
            phoneNumber: phone,
          })
        } else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },

  changeImg: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认最多上传9张
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        var tempFilePaths = res.tempFilePaths; // 返回选定照片的本地路径列表 
        // that.setData({
        //   photoList: tempFilePaths,
        //   photo: tempFilePaths[0]
        // })
        // that.sendImge()
          wx.navigateTo({
        url: '../image/image?imagePath='+tempFilePaths[0]+"&type=1"
      })
      }

    })
    console.log(this.data.photo)

  },


  sendImge: function () {
    wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
    wx.showLoading({ //显示 loading 提示框
      title: "处理中...",
    })
    for (var i = 0; i < this.data.photoList.length; i++) {
      var timestamp = Date.parse(new Date());
      timestamp = timestamp / 1000;
      var _this = this
      var filepath = this.data.photoList[i]
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
      qiniuUploader.upload(filepath, res => {
        console.log(res)
        var url = res.fileUrl
        _this.saveData(url)
      }, (error) => {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        wx.showToast({
          title: "修改头像失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
        return;
      }, {
        key: "jygy/" + "photo/" + app.globalData.schoolId + "/" + app.globalData.classid + "/" + timestamp + "/" + utils.formatDate(new Date()) + utils.wxuuid() + ".jpg",
        region: 'NCN',
        uptoken: _this.data.qiniuToken,
        uploadURL: 'https://up-z1.qbox.me',
        domain: app.globalData.qiniurUrl,
      })
    }
  },

  saveData: function (url) {

    var map = {
      "headicon": url
    }
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "mobileType": app.globalData.mobileType,
      "update": map,
      "timeSpan": app.globalData.timespan,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "modify_teacher_info"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        console.log(res)
        if (res.data.status == 0) {
          wx.showToast({
            title: "修改头像成功",
            icon: 'none',
            duration: 1000,
            mask: true
          })
          app.globalData.photo = url
          that.setData({
            photo: url
          })
        } else {
          wx.showToast({
            title: "修改头像失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
        }

      },
      fail: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        wx.showToast({
          title: "修改头像失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
      },
      complete: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        console.log('submit complete');
      }
    })
  },

  getQiniuToken: function (e) {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan
    }
    wx.request({
      url: app.globalData.serverQiNiuUrl,
      data: {
        "data": JSON.stringify(data)
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          that.setData({
            qiniuToken: res.data.data.token
          })
        } else {

        }
      },
      fail: function (res) {

      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },





  btnAbout: function (e) {
    wx.navigateTo({
      url: '../about/about'
    })

  },

  btnCardSet: function (e) {
    wx.navigateTo({
      url: '../cardsetdetail/cardsetdetail'
    })
  },



  //退出登录
  btnClick: function (e) {
    this.logout()

  },
  /*点击变色*/
  click: function (e) {
    var id = e.currentTarget.dataset.id
    var that = this
    that.setData({
      id: id
    })
  },
  logout: function (e) {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "logout"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {

        if (res.data.status == 0) {
          wx.setStorageSync('pwd', ""); //清空密码
          app.globalData.islogin = false
          wx.redirectTo({
            url: '../login/login'
          })
        }else{
          wx.showToast({
            title: "退出失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
        }


      },
      fail: function (res) {
        wx.showToast({
          title: "退出失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },

  btnSafeSet: function (e) {
    wx.navigateTo({
      url: '../safeset/safeset'
    })
  },

  btnFaceSet: function (e) {

    //请求数据是否此孩子所在幼儿园存在人脸闸机,如果存在人脸闸机则跳转，否则提示人脸注册功能暂未开放
    wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
    wx.showLoading({ //显示 loading 提示框
      title: "正在获取数据...",
    })
    var that = this;
    wx.request({
      url: app.globalData.serverFaceUrl,
      data: {
        'schoolId': app.globalData.schoolId,
        'cmd': 'getfacemachine'
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        console.log(res);
        if (res.data.status == 0) {
          var count = res.data.count;
          if (count > 0) {

            that.getData();

          } else {
            wx.showToast({
              title: "【人脸注册】功能暂未开放",
              icon: 'none',
              duration: 3000,
              mask: true
            })
          }
        } else {
          wx.showToast({
            title: "获取数据失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
        }

      },
      fail: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        wx.showToast({
          title: "获取数据失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },

  getData: function (e) {
    wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
    wx.showLoading({ //显示 loading 提示框
      title: "正在刷新...",
    })
    wx.request({
      url: app.globalData.serverFaceUrl,
      data: {
        'teacherId': app.globalData.userId,
        'schoolId': app.globalData.schoolId,
        'cmd': 'getteachermess'
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        console.log(res);
        if (res.data.status == 0) {

          var teacherMess = res.data.data.user;
          if (teacherMess != null) {

            if (teacherMess.haveface == 0) {
              //请求数据是否教师所在幼儿园存在人脸闸机,如果存在人脸闸机则跳转，否则提示人脸注册功能暂未开放
              wx.navigateTo({
                url: '../guidepage/guidepage?userId=' + app.globalData.userId + '&userName=' + app.globalData.name + "&userType=" + 2
              })
            } else {
              var map = JSON.stringify(teacherMess);
              wx.navigateTo({
                url: '../previewface/previewface?map=' + map
              })
            }
          } 

        } else {
          wx.showToast({
            title: "获取数据失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
        }

      },
      fail: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        wx.showToast({
          title: "获取数据失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  }

})